<?php
/**
 * @title 889. 根据前序和后序遍历构造二叉树
 * @author start2004
 */

// ini_set("memory_limit", "128M");

// class Solution {
//
//     function find() {
//
//     }
// }


class Solution {

    /**
     * @param Integer[] $preorder
     * @param Integer[] $postorder
     * @return TreeNode
     */
    function constructFromPrePost($preorder, $postorder) {
        if(empty($preorder)) return null;

        /**
         * @since 2024-02-22 前序遍历preorder，root+left+right
         * @since 2024-02-22 后序遍历postorder，left+right+root
         */
        $val = $preorder[0];
        $tree = new TreeNode($val);
        if(isset($preorder[1])){
            /**
             * @since 2024-02-22 左子树的leftRoot
             */
            $leftRoot = $preorder[1];
            $leftRootIndex = array_search($leftRoot, $postorder);

            /**
             * @since 2024-02-22 左子树，右子树的前序，后序遍历
             */
            $leftPreorder = array_slice($preorder, 1, $leftRootIndex+1);
            $leftPostorder = array_slice($postorder, 0, $leftRootIndex+1);
            $rightPreorder = array_slice($preorder, $leftRootIndex+2);
            $rightPostorder = array_slice($postorder, $leftRootIndex+1, count($rightPreorder));

            $tree->left = $this->constructFromPrePost($leftPreorder, $leftPostorder);
            $tree->right = $this->constructFromPrePost($rightPreorder, $rightPostorder);
        } else {}

        /**
         * @return
         */
        return $tree;
    }
}



/**
 * @url http://127.0.0.1/leetcode/202402/2024.02.22.php
 */
$datas = [

];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    /**
     * @since 2024-01-15 超时和错误案例参数
     */
    // $data = $xhprof->FormatArgs("/tmp/leetcode/xxx-xxx.txt");

    // $data[0] = $xhprof->listNode($data[0]);
    // $data[0] = $xhprof->tree($data[0]);
    echo $xhprof->DumpArgs($data);
    echo "\n<hr>\n";

    $obj = new Solution();
    $result = $obj->(...$data);
    echo $xhprof->DumpArgs([$result]);
    var_dump($result);

    echo "\n<hr>". str_repeat("<br>", 2) . str_repeat(PHP_EOL, 5);
}

// foreach ($datas as $data){
//     $obj = new $data[0][0](...$data[1][0]);
//
//     for ($i=1; $i<count($data[0]); $i++){
//         $func = $data[0][$i];
//         $param = $data[1][$i];
//         $result = $obj->$func(...$param);
//
//         echo $data[0][$i] ."(\"". implode(",", $data[1][$i]) ."\") ";
//             if($result === true){
//                 echo "True";
//             } elseif($result === false) {
//                 echo "False";
//             } elseif($result === null) {
//                 echo "Null";
//             } elseif(is_array($result)) {
//                 var_dump($result);
//             } else {
//                 echo $result;
//             }
//         echo PHP_EOL;
//     }
//
//     echo str_repeat(PHP_EOL, 3);
// }
$xhprof->end();
